package com.freedom.web.mymvc.utils;

import java.io.File;
import java.io.FileInputStream;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class FileUtils {
	private static int BUFFER_SIZE = 8192;
	// logger
	private static final Logger logger = LogManager.getLogger(FileUtils.class);

	public static String getFileContent(String fileName) throws Exception {
		LoggerUtils.debug(logger,
				"current direcotry:" + new File(".").getAbsolutePath() + " try to get content for " + fileName);
		// 老规矩，参数校验
		if (null == fileName || fileName.trim().length() == 0) {
			LoggerUtils.error(logger, "invalid filename: " + fileName);
			throw new Exception("invalid filename: " + fileName);
		}

		try {
			byte[] buffer = new byte[BUFFER_SIZE];
			int byteRead;

			// 开始读
			fileName = fileName.trim();
			FileInputStream in = new FileInputStream(fileName);
			StringBuilder out = new StringBuilder("");
			while ((byteRead = in.read(buffer)) != -1) {
				out.append(new String(buffer, 0, byteRead));
			}
			String fileContent = out.toString();
			// 务必要关闭文件句柄!!!
			in.close();
			in = null;
			out = null;
			// 现场清理完毕，返回结果
			return fileContent;
		} catch (Exception e) {
			LoggerUtils.error(logger, e.toString());
			throw new Exception(e);
		}
	}

	// 获取文件类型
	public static String getFileType(String fileName) {
		if (null == fileName) {
			return null;
		}
		// 开始走分支
		fileName = fileName.trim();
		if (fileName.endsWith(".js")) {
			return ConstantsUtils.JAVASCRIPT;
		} else if (fileName.endsWith(".css")) {
			return ConstantsUtils.CSS;
		} else if (fileName.endsWith(".png")) {
			return ConstantsUtils.PNG;
		} else if (fileName.endsWith(".gif")) {
			return ConstantsUtils.GIF;
		} else if (fileName.endsWith(".jpg")) {
			return ConstantsUtils.JPG;
		} else if (fileName.endsWith(".svg")) {
			return ConstantsUtils.SVG;
		} else {
			return null;// 未纳入识别体系的
		}
	}
}
